package com.qh.controller;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qh.service.impl.CommonServiceImpl;
import com.qh.util.Constants;
import com.qh.util.ConvertUtil;

@Controller
public class CommonController {

	@Resource
	private CommonServiceImpl service;

	/**
	 * 查询
	 * 
	 * @param req
	 * @return 查询结果
	 */
	@RequestMapping("/query.do")
	@ResponseBody
	public Map<String, Object> query(HttpServletRequest req) {

		Map<String, Object> resultMap = new HashMap<>();
		Map<String, String> parameterMap = new HashMap<>();

		Enumeration<String> parameterNames = req.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = (String) parameterNames.nextElement();
			parameterMap.put(parameterName, req.getParameter(parameterName));
		}

		resultMap = this.service.getObjectList(parameterMap);
		
		// 用户登录
		if ("user.S002".equals(parameterMap.get("queryID"))) {
			// 用户id存入session
			if ("1".equals(resultMap.get("count"))) {
				@SuppressWarnings("unchecked")
				List<Map<String, Object>> dataList = (List<Map<String, Object>>) resultMap.get("dataList");
				Map<String, Object> userMap = dataList.get(0);
				req.getSession().setAttribute(Constants.LoginUser, userMap);
			}
		}

		return resultMap;
	}

	/**
	 * 保存
	 * 
	 * @param req
	 * @return 保存结果
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/save.do")
	@ResponseBody
	public Map<String, String> save(HttpServletRequest req) {

		Map<String, String> resultMap = new HashMap<>();
		Map<String, String> parameterMap = new HashMap<>();
		
		String action = null; // "create" or "update"
		String append = null; // "all" or "time" or "user"
		String userid = null;

		// 获取参数
		Enumeration<String> parameterNames = req.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = (String) parameterNames.nextElement();
			if ("action".equals(parameterName)) {
				action = req.getParameter(parameterName);
			} else if ("append".equals(parameterName)) {
				append = req.getParameter(parameterName);
			} else {
				parameterMap.put(parameterName, req.getParameter(parameterName));
			}
		}

		// 获取当前登录用户
		Map<String, Object> LoginUser = (Map<String, Object>) req.getSession().getAttribute(Constants.LoginUser);
		if (LoginUser != null) {
			if (LoginUser.get("id") != null) {
				userid = String.valueOf(LoginUser.get("id"));
			}
		}
		
		if ("create".equals(action)) {
			if ("all".equals(append)) {
				if (userid != null) {
					parameterMap.put("createUser", userid);
					parameterMap.put("updateUser", userid);
				}
				parameterMap.put("createTime", ConvertUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss"));
				parameterMap.put("updateTime", parameterMap.get("createTime"));
			} else if ("time".equals(append)) {
				parameterMap.put("createTime", ConvertUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss"));
				parameterMap.put("updateTime", parameterMap.get("createTime"));
			} else if ("user".equals(append)) {
				if (userid != null) {
					parameterMap.put("createUser", userid);
					parameterMap.put("updateUser", userid);
				}
			}
			resultMap = this.service.save(parameterMap);
		} else if ("update".equals(action)) {
			if ("all".equals(append)) {
				if (userid != null) {
					parameterMap.put("updateUser", userid);
				}
				parameterMap.put("updateTime", ConvertUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss"));
			} else if ("time".equals(append)) {
				parameterMap.put("updateTime", ConvertUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss"));
			} else if ("user".equals(append)) {
				if (userid != null) {
					parameterMap.put("updateUser", userid);
				}
			}
			resultMap = this.service.save(parameterMap);
		} else {
			resultMap.put("code", "9"); // skip
		}

		return resultMap;
	}

	/**
	 * 删除
	 * 
	 * @param req
	 * @return 删除结果
	 */
	@RequestMapping("/remove.do")
	@ResponseBody
	public Map<String, String> remove(HttpServletRequest req) {

		Map<String, String> resultMap = new HashMap<>();
		Map<String, String> parameterMap = new HashMap<>();

		Enumeration<String> parameterNames = req.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = (String) parameterNames.nextElement();
			parameterMap.put(parameterName, req.getParameter(parameterName));
		}

		resultMap = this.service.delete(parameterMap);

		return resultMap;
	}
	
	/**
	 * 发送短信验证码
	 * 
	 * @param req
	 * @return 发送短信验证码处理结果
	 */
	@RequestMapping("/sendCode.do")
	@ResponseBody
	public Map<String, String> sendCode(HttpServletRequest req) {
		
		Map<String, String> resultMap = new HashMap<>();
		Map<String, String> parameterMap = new HashMap<>();
		
		Enumeration<String> parameterNames = req.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = (String) parameterNames.nextElement();
			parameterMap.put(parameterName, req.getParameter(parameterName));
		}
		parameterMap.put("table", "code");
		parameterMap.put("code", ConvertUtil.date2String(new Date(), "HHmmss"));
		parameterMap.put("createTime", ConvertUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss"));
		parameterMap.put("updateTime", parameterMap.get("createTime"));
		
		resultMap = this.service.save(parameterMap);
		
		return resultMap;
	}

	/**
	 * 页面跳转控制
	 * 
	 * @param viewName
	 * @param req
	 * @return 跳转页面及数据
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "wx/{viewName}.do")
	public ModelAndView dispatch(@PathVariable(value = "viewName") String viewName, HttpServletRequest req) {

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("/" + viewName);
		
		Enumeration<String> parameterNames = req.getParameterNames();
		// 参数存入session，防止浏览器刷新页面时参数丢失
		Map<String, String> parameterMap = new HashMap<>();
		
		while (parameterNames.hasMoreElements()) {

			String parameterName = (String) parameterNames.nextElement();
			String parameter = req.getParameter(parameterName);

			modelAndView.addObject(parameterName, parameter);

			// 参数存入session，防止浏览器刷新页面时参数丢失
			parameterMap.put(parameterName, parameter);
		}
		
		// 参数存入session，防止浏览器刷新页面时参数丢失
		if (parameterMap.isEmpty()) {
			try {
				
				parameterMap = (Map<String, String>)req.getSession().getAttribute(viewName);
				if (parameterMap != null) {					
					for (Entry<String, String> entry : parameterMap.entrySet()) {
						
						modelAndView.addObject(entry.getKey(), entry.getValue());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {			
			
			// 参数存入session，防止浏览器刷新页面时参数丢失
			req.getSession().setAttribute(viewName, parameterMap);
		}

		return modelAndView;
	}

}
